<template>
  <div class="playlist" v-if="playlist">
    <PlaylistHeader>{{ playlist.name }}</PlaylistHeader>

    <!-- 头部信息 -->
    <div class="header">
      <div
        class="mask"
        :style="{ backgroundImage: `url(${playlist.coverImgUrl})` }"
      ></div>

      <div class="top">
        <div class="thumb">
          <img :src="playlist.coverImgUrl | completeImageUrl" alt="" />

          <div class="msg">
            <div class="icon icon_base"></div>
            <span>{{ playlist.playCount | parsePlayCount }}</span>
          </div>
        </div>

        <div class="right">
          <div class="top">{{ playlist.name }}</div>

          <div class="bottom" v-if="playlist.creator">
            <div class="icon">
              <img
                :src="playlist.creator.avatarUrl | completeImageUrl"
                alt=""
              />
            </div>
            <div class="nick">{{ playlist.creator.nickname }}</div>

            <div class="btn" :class="{ active: isFollow }">
              <span
                v-if="!isFollow"
                @click="
                  addFollowPlaylistAuthors({ id: playlist.creator.userId })
                "
              >
                +关注
              </span>
              <span
                v-else
                @click="
                  removeFollowPlaylistAuthors({ id: playlist.creator.userId })
                "
              >
                已关注
              </span>
            </div>
          </div>
          <div class="description e_1" @click="toPlaylistDetail(playlist.id)">
            {{ playlist.description }}
          </div>
        </div>
      </div>

      <div class="bottom">
        <!-- 工具条 -->
        <div class="tool-bar">
          <div class="left">
            <!-- 分享面板 -->
            <div class="item icon_base" @click="showShare = true"></div>

            <!-- 添加到稍后听 -->
            <div
              class="item icon_base"
              @click="addPlaylistFootprintsWithTips({ playlist })"
            ></div>

            <!-- 歌单漫游 -->
            <div class="item icon_base"></div>

            <!-- 歌单评论 -->
            <div
              class="item icon_base"
              @click="toCommentArea(playlist.id)"
            ></div>
          </div>

          <div class="right">
            <div class="left">
              <img
                src="../../assets/kugou/已关注.png"
                v-if="isSubPlaylist"
                @click="removeSubPlaylists({ id: playlist.id })"
              />
              <img
                src="../../assets/kugou/未关注.png"
                v-else
                @click="addSubPlaylists({ id: playlist.id })"
              />
            </div>

            <div class="right">{{ playlist.subscribedCount }}人收藏></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 歌曲 -->
    <div class="list">
      <!-- 搜索 -->
      <header v-if="isSearching">
        <van-search
          v-model="value"
          show-action
          placeholder="搜索此歌单的歌曲"
          @cancel="isSearching = false"
          @search="onSearch"
        />
      </header>

      <!-- 播放全部 -->
      <header v-else-if="!isSearching">
        <div
          class="left"
          @click="addAllSongIntoPlaylist({ list: playlist.tracks })"
        >
          <div class="icon icon_base"></div>
          <div class="text">播放全部</div>
          <div class="total" v-if="playlist.tracks">
            {{ playlist.tracks.length }}
          </div>
        </div>

        <div class="right">
          <!-- 搜索 -->
          <div class="item icon_base" @click="scrollToElement"></div>
          <!-- 排序方式 -->
          <div class="item icon_base" @click="isShowSortMask = true"></div>
          <!-- 编辑 -->
          <div class="item icon_base" @click="isShowPreCheckedbox = true"></div>
        </div>
      </header>

      <!-- 显示前面多选框 -->
      <div v-if="isShowPreCheckedbox" class="checked-tool">
        <div class="left">
          {{ checkedCount }}/{{ playlist.tracks.length }}首
        </div>

        <div class="right" @click="isShowPreCheckedbox = false">完成</div>
      </div>

      <!-- 歌曲列表 -->
      <van-list
        v-model="loading"
        loading-text="没有更多了"
        finished-text="没有更多了"
        @load.once="loadMore"
        error-text="请求失败，请检查网络"
        :immediate-check="false"
      >
        <SongListItem
          v-for="item in playlist.tracks"
          :key="item.id"
          :item="item"
          @click.native="addPlaylistFootprints({ playlist })"
          :isShowPreCheckedbox="isShowPreCheckedbox"
        />
      </van-list>
    </div>

    <van-share-sheet
      v-model="showShare"
      title="立即分享给好友"
      :options="options"
    />

    <section v-show="simiPlaylst.length">
      <HomeTitle>相似歌单推荐</HomeTitle>
      <ul>
        <PlayListCard
          v-for="item in simiPlaylst"
          :key="item.id"
          :item="item"
          @click.native="updatePlaylistData(item.id)"
        />
      </ul>
    </section>

    <transition
      name="custom-classes-transition"
      enter-active-class="animated fadeInUp"
      leave-active-class="animated fadeOutDown"
    >
      <SortMask v-show="isShowSortMask" />
    </transition>
  </div>
</template>

<script>
import PlaylistHeader from "@/components/slot/headerbox/CustomHeader.vue";
import SongListItem from "@/components/basics/SongListItem.vue";
import HomeTitle from "@/components/slot/HomeTitle.vue";

import { mapState, mapMutations } from "vuex";
import PlayListCard from "@/components/basics/PlayListCard.vue";

import SortMask from "@/components/toggle/SortMask.vue";

export default {
  components: {
    PlaylistHeader,
    SongListItem,
    HomeTitle,
    PlayListCard,
    SortMask,
  },
  name: "Playlist",
  created() {
    const { id } = this.$route.query;
    this.initPlaylistData(id);
  },
  data() {
    const options = [
      [
        { name: "微信", icon: "wechat" },
        { name: "朋友圈", icon: "wechat-moments" },
        { name: "微博", icon: "weibo" },
        { name: "QQ", icon: "qq" },
      ],
      [
        { name: "复制链接", icon: "link" },
        { name: "分享海报", icon: "poster" },
        { name: "二维码", icon: "qrcode" },
        { name: "小程序码", icon: "weapp-qrcode" },
      ],
    ];
    return {
      playlist: {},
      showShare: false,
      options,
      simiPlaylst: [],

      // 搜索
      isSearching: false,
      value: "",

      // 是否显示排序方式蒙层
      isShowSortMask: false,

      // 是否开启前置多选框
      isShowPreCheckedbox: false,

      // van-list的两个状态
      loading: false,
      finished: true,
    };
  },

  computed: {
    ...mapState([
      "playlistFootprints",
      "followPlaylistAuthors",
      "subPlaylists",
      "currentSong",
      "currentTime",
    ]),

    // 是否关注歌单作者
    isFollow() {
      const { userId } = this.playlist.creator;
      return this.followPlaylistAuthors.includes(userId);
    },

    // 是否收藏歌单
    isSubPlaylist() {
      return this.subPlaylists.includes(this.playlist.id);
    },

    // 当前已经选中了多少首歌
    checkedCount() {
      return this.playlist.tracks
        .map((item) => item.isChecked)
        .filter((flag) => flag !== undefined && flag === true).length;
    },
  },
  methods: {
    ...mapMutations([
      "addFollowPlaylistAuthors",
      "removeFollowPlaylistAuthors",
      "addPlaylistFootprints",
      "removeSubPlaylists",
      "addSubPlaylists",
      "addAllSongIntoPlaylist",
      "addPlaylistFootprintsWithTips",
    ]),

    /**
     * 获取相似歌单
     * @param {number} id  歌曲id
     */
    async getSimiPlayList(id) {
      const res = await this.axios.get(`/simi/playlist?id=${id}`);
      this.simiPlaylst = res.data.playlists;

      setTimeout(() => {
        this.$toast({
          type: "success",
          message: "已更新相似歌单推荐",
          position: "middle",
        });
      }, 1000);
    },

    // 更新路由&歌单内容
    updatePlaylistData(id) {
      this.$router.push({ path: "/playlist", query: { id } });
    },

    /**
     * 初始化歌单数据
     * @param id 歌单id
     */
    async initPlaylistData(id) {
      // 获取歌单详情
      const res = await this.axios({ url: "/playlist/detail", params: { id } });
      this.playlist = res.data.playlist;

      // 当前有歌才获取相似歌单
      if (this.currentSong) {
        console.log("initPlaylistData-if");
        this.getSimiPlayList(this.currentSong.id);
      }
    },

    // 点击搜索按钮，滚动到指定位置，并显示搜索框
    scrollToElement() {
      const top = 230; // 顶端距离

      scrollTo({
        behavior: "auto",
        top, // top: top
      });
      this.isSearching = true;
    },
    // 按下回车触发-关键词过滤功能

    // 防抖
    onSearch(value) {
      // 如果正在搜索
      if (this.isSearching) {
        // 如果输入框为空，恢复到初始的 playlist 数据
        if (value.trim() === "") {
          const { id } = this.$route.query;
          this.initPlaylistData(id);
        } else {
          console.log("else");
          const search_result = this.playlist.tracks.filter((item) =>
            item.name.toLowerCase().includes(value.toLowerCase())
          );

          this.playlist.tracks = search_result;

          /*
            TODO匹配高亮
              ig
                i-忽略大小写
                g-全局匹配
              const reg = new RegExp(value, "ig");
           */
        }
      }
    },

    // 顶部绑定值变化时触发
    handChange(flag) {
      this.playlist.tracks.forEach((song) => {
        this.$set(song, "isChecked", flag);
        song.isChecked = flag;
      });
    },

    // 跳转至歌单详情
    toPlaylistDetail(id) {
      const { coverImgUrl, name, description, createTime } = this.playlist;
      const { avatarUrl, expertTags, nickname } = this.playlist.creator;

      const query = {
        id,
        coverImgUrl,
        nickname,
        avatarUrl,
        expertTags,
        name,
        description,
        createTime,
      };

      this.$router.push({ path: "/playlist_detail", query });
    },

    // 点击进入评论区
    toCommentArea(id) {
      const { coverImgUrl, name } = this.playlist;

      const query = {
        id,
        coverImgUrl,
        name,
      };
      this.$router.push({ path: "/playlist_comments", query });
    },

    /**
     * 延时10秒模拟触底加载更多歌单歌曲，拼接加载歌单内全部音乐
     *
     * 1.获取歌单内所有的歌曲id，过滤出歌单已有的歌曲
     * 2.获取到的过滤id，调用后台接口获取歌曲名等信息
     * 3.拼接到现有的歌单列表
     */
    loadMore() {
      console.log("执行了loadMore");
      const DELAY_MS = 10000;
      const timer = setTimeout(async () => {
        this.$toast.loading({
          position: "middle",
          message: "正在加载",
        });
        if (this.playlist.trackIds && this.playlist.trackIds.length > 21) {
          console.log("loadMore-if");
          // 获取歌单内所有的歌曲id
          const ids = this.playlist.trackIds
            .slice(21)
            .map((item) => item.id)
            .join(",");

          // 获取到的过滤id，调用后台接口获取歌曲名等信息
          const res = await this.axios.get(`/song/detail?ids=${ids}`);

          // 拼接到现有的歌单列表，看我骚操作
          const { songs: tracks } = res.data; // const tracks = res.data.songs;

          // this.playlist.tracks = this.playlist.tracks.concat(tracks);
          this.playlist.tracks.push(...tracks);

          this.$toast({
            type: "success",
            message: "已加载歌单内全部音乐",
            position: "middle",
          });

          if (this.playlist.tracks.length > 20) {
            // 清除定时器
            clearTimeout(timer);
            this.endLoad();
          }
        }
      }, DELAY_MS);
    },

    // 手动结束van-list的加载
    endLoad() {
      console.log("----------正在结束----------");
      // 设置加载状态为false
      this.loading = false;
      // 数据全部加载完成
      this.finished = true;
      console.log("----------结束完成----------");
    },
  },

  watch: {
    // 根据当前音乐获取相似歌单列表
    "currentSong.id"(n) {
      // 这里防止清空歌单还会继续执行获取相似歌单的方法
      if (n) {
        this.getSimiPlayList(n);
      }
    },

    // 是否正在搜索
    isSearching(isSearching) {
      // 如果不在搜索就初始化数据
      if (!isSearching) {
        const { id } = this.$route.query;
        this.initPlaylistData(id);
      }
    },
  },

  // 当点击相似歌单时，触发使用路由守卫
  beforeRouteUpdate(to, from, next) {
    console.log("to, from, next => ", to, from, next);
    this.initPlaylistData(to.query.id);
    // 滚动到最上方
    scrollTo({ top: 0, behavior: "smooth" });
    next();
  },

  // TODO 现在存在跳转到相似歌单后，会自动加载歌单全部音乐，无法重置列表状态
  // beforeRouteLeave(to, from, next) {
  //   console.log("beforeRouteLeave");

  //   // this.loading = false;
  //   // this.finished = false;
  //   next();
  // },
};
</script>

<style lang="less" scoped>
.playlist {
  width: 100%;
  margin-top: 50px;

  .header {
    position: relative;
    overflow: hidden;
    padding: 15px;
    transition: all 1s;

    .mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      // 模糊度，亮度
      filter: blur(30px) brightness(0.6);
      transform: scale(1.5);
      background-position: center center;
      background-repeat: no-repeat;
    }

    .top {
      width: 100%;
      display: flex;
      align-items: center;

      .thumb {
        width: 125px;
        position: relative;

        .msg {
          position: absolute;
          bottom: 5px;
          right: 0;
          height: 30px;
          color: #fff;
          background-color: #707070b4;
          border-radius: 10px;
          display: flex;
          align-items: center;
          font-size: 10px;

          .icon {
            width: 30px;
            height: 100%;
            background-image: url("../../assets/播放白色实心.png");
          }

          span {
            color: white;
            font-size: 14px;
            /* offset-x | offset-y | blur-radius | color */
            text-shadow: 6px -3px 7px #707070;
          }
        }
      }

      .right {
        width: 210px;
        height: 120px;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        font-weight: bold;
        padding-left: 20px;

        .bottom {
          width: 100%;
          height: 30px;
          display: flex;
          align-items: center;
          font-weight: normal;

          .icon {
            width: 30px;
            height: 100%;
            text-align: center;
            line-height: 30px;

            img {
              vertical-align: middle;
              border-radius: 50%;
            }
          }

          .nick {
            font-size: 12px;
            padding-left: 10px;
          }

          .btn {
            width: 60px;
            height: 100%;
            border: 1px solid #80737a;
            color: #000;
            border-radius: 10px;
            text-align: center;
            line-height: 30px;
            font-size: 14px;
            font-weight: bold;

            &.active {
              color: #80737a;
            }
          }
        }

        .description {
          width: 100%;
          font-size: 12px;
        }
      }
    }
  }

  .tool-bar {
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left {
      width: 60%;
      height: 80%;
      display: flex;
      justify-content: space-between;

      .item {
        width: 20%;
        height: 100%;
        background-color: #dfcdc9;
        border-radius: 50%;

        &:nth-of-type(1) {
          background-image: url("../../assets/kugou/分享.png");
        }
        &:nth-of-type(2) {
          background-image: url("../../assets/kugou/加.png");
        }
        &:nth-of-type(3) {
          background-image: url("../../assets/kugou/gis_漫游.png");
        }
        &:nth-of-type(4) {
          background-image: url("../../assets/kugou/评论.png");
        }
      }
    }

    .right {
      width: 35%;
      height: 80%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #c3b4b1;
      border-radius: 20px;

      .left {
        width: 40px;
        height: 100%;
        background-color: #dfcdc9;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;

        img {
          width: 25px;
          height: 25px;
        }
      }

      .right {
        font-size: 9px;
        color: #7d6f6c;
        width: 70px;
      }
    }
  }

  .list {
    width: 100%;
    padding: 10px;
    background-color: #fff;

    header {
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: space-between;
      margin: 15px 0;
      position: sticky;
      top: 50px;
      z-index: 5;
      background-color: #fff;

      .left {
        width: 140px;
        height: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .icon {
          width: 30px;
          height: 100%;
          background-image: url("../../assets/kugou/播放.png");
          background-size: contain;
        }

        .text {
          font-weight: bold;
        }

        .total {
          color: #707070;
        }
      }

      .right {
        width: 160px;
        height: 100%;
        display: flex;
        justify-content: space-between;

        .item {
          width: 40px;
          height: 100%;

          &:nth-of-type(1) {
            background-image: url("../../assets/kugou/搜索.png");
          }

          &:nth-of-type(2) {
            background-image: url("../../assets/kugou/排序.png");
          }

          &:nth-of-type(3) {
            background-image: url("../../assets/kugou/批量选择.png");
          }
        }
      }
    }

    .checked-tool {
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: sticky;
      top: 85px;
      background-color: #fff;
      z-index: 6;

      .left,
      .right {
        line-height: 40px;
      }

      .left {
        flex: 1;
        padding-left: 10px;
        font-size: 12px;
        color: #707070;
      }
    }
  }

  ul {
    display: flex;
  }
}
</style>
